package com.transcargo.request;

import com.transcargo.action.ServletParametersException;
import com.transcargo.action.ServletValidationException;
import com.transcargo.geo.GeoObjectNotFoundException;
import com.transcargo.rpc.RPCOutput;
import com.transcargo.users.ShortUser;
import com.transcargo.users.User;
import com.transcargo.users.UserNotFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.PrintWriter;
import java.io.IOException;

/**
 * Date: 24.04.2011
 * Time: 16:10:39
 */
public class GetUserRequest extends Request
{
	private String uid = "";
	private String xml = "";
	Boolean s = false;

    private void servletGetValues(HttpServletRequest request) throws ServletParametersException {
		uid = request.getParameter("uid");
		if (uid == null) uid = "";
		String sh = request.getParameter("short");
		if (sh != null && sh.equals("on")) s = true;
    }
    private void servletValidateValues() throws ServletValidationException {
    	if (uid.length() == 0) throw new ServletValidationException("Empty uid");
    }
    private void servletExecuteRequest() throws ServletRequestException {
    	try {
    		if (s) {
        		ShortUser user = new ShortUser(Integer.parseInt(uid), dbase);
        		xml =  RPCOutput.generate(user);
    		} else {
    			User user = new User(Integer.parseInt(uid), dbase);
    			xml =  RPCOutput.generate(user);
    		}
    	} catch (GeoObjectNotFoundException e) {
    		throw new ServletRequestException();
    	} catch (UserNotFoundException e) {
    		throw new ServletRequestException();
		}
    }
    public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        PrintWriter out = null;
		try {
            out = response.getWriter();
            servletGetValues(request);
            servletValidateValues();
            servletExecuteRequest();
            out.println(xml);
	    } catch (ServletParametersException e) {
           sendRedirect(response, "index.jsp");
        }  catch (ServletValidationException e) {
            sendError(response, new Exception(e.getMessage()));
        }  catch (ServletRequestException e) {
            String xml =  RPCOutput.generate(false);
            out.println(xml);
        }  catch (IOException e) {
            System.out.println("IOException: " + e.getMessage());
        }
    }
}
